<?php
namespace Plugin\Controller;
use Think\Controller;
use Think\Model;
class ChatController extends Controller{
	/**
	 * @desc 保存聊天内容
	 * @param int touid 必须 接收者ID
	 * @param string content 发送内容
	 * @param int uid 必须 发送者ID
	 * @param string send_time 发送时间
	 */
    public function save_message(){
		if($_POST['touid'] && $_POST['content'] && $_POST['uid'] && $_POST['send_time']){
			D('ChatContent')->add($_POST);
		}else{
			_apiReturn(0, '信息保存失败', $data, $url);
		}
    }
	
	/**
	 * @desc 获取聊天内容
	 * @param int uid 必须 我的ID
	 * @param int touid 必须 对象ID
	 */
	public function get_message(){
		$uid = I('uid');
		$touid = I('touid');
		$p = I('p');
		$row = I('row');
		if(!$p) $p = 1;
		if(!$row) $row = 10;
		if($uid && $touid){
			$sql = "SELECT A.*,B.`avater`,B.`username`,C.`avater`AS'to_avater',C.`username`AS'to_username' FROM mini_chat_content A JOIN mini_users B ON A.`uid`=B.`uid` JOIN mini_users C ON A.`touid`=C.`uid` WHERE (A.`uid`=".$uid." AND A.`touid`=".$touid.") OR (A.`uid`=".$touid." AND A.`touid`=".$uid.")";
			$sqlcount = "SELECT count(DISTINCT A.id) as tp_count FROM mini_chat_content A JOIN mini_users B ON A.`uid`=B.`uid` JOIN mini_users C ON A.`touid`=C.`uid` WHERE (A.`uid`=".$uid." AND A.`touid`=".$touid.") OR (A.`uid`=".$touid." AND A.`touid`=".$uid.")";
			
			$sql .= ' ORDER BY A.`send_time` DESC';
			$sql .= ' limit '.($p-1)*$row.','.$row;
			
			$model = new Model();
			$info = $model->query($sql);
			$count = $model->query($sqlcount);
			if($info){
				$data['data'] = $info;
				$data['total'] = $count[0]['tp_count'];
//				$data['page']['total'] = $count[0]['count'];
//				$data['page']['cur'] = $p;
//				$data['page']['row'] = $row;
				_apiReturn(1, "获取成功", $data, $url);
			}else{
				_apiReturn(0, '暂无聊天数据', $data, $url);
			}
			
		}else{
			_apiReturn(0, 'ID不能为空', $data, $url);
		}
	}
	
	/**
	 * @desc 获取聊天内容
	 * @param int uid 必须 我的ID
	 */
	public function get_chat_list(){
		$uid = I('uid');
		if($uid){
			$sql = "SELECT A.`uid`,MAX(A.`send_time`) AS 'send_time',B.`username`,B.`avater` FROM mini_chat_content A JOIN mini_users B ON A.`uid`=B.`uid` WHERE A.`touid`=".$uid." GROUP BY A.`uid` ORDER BY send_time DESC";
			$model = new Model();
			$info = $model->query($sql);
			if($info){
				_apiReturn(1, "获取成功", $info, $url);
			}else{
				_apiReturn(0, '暂无聊天数据', $data, $url);
			}
			
		}else{
			_apiReturn(0, 'ID不能为空', $data, $url);
		}
	}
	
	/**
	 * @desc 搜索联系人
	 * @param string keyword 必须 关键词-用户名
	 */
	public function search_user(){
		$keyword = I('keyword');
		if($keyword){
			$sql = "SELECT A.`username`,A.`avater`,A.`uid`,B.`title` FROM mini_users A JOIN mini_schools B ON A.`sid`=B.`sid` WHERE A.`username`='".$keyword."'";
			$model = new Model();
			$info = $model->query($sql);
			if($info){
				_apiReturn(1, "搜索成功", $info, $url);
			}else{
				_apiReturn(0, '该用户不存在', $data, $url);
			}
			
		}
	}
}